package services

import (
	"encoding/json"
	"github.com/nats-io/nuid"
	"im/app/conf"
	"im/app/models"
	"im/app/models/form/message"
	"im/rabbitmq"
	"time"
)

type MessageService struct {

}

func (ms *MessageService) Add(inputs *message.MessageControllerAdd) (*models.Messages, error) {
	// 消息保存起来
	n := nuid.New()
	nuid := n.Next()
	messsage := models.Messages{
		ID:        0,
		MsgID: nuid,
		UserID:    inputs.Userid,
		DstId:     inputs.Dstid,
		Content:   inputs.Content,
		Pic:       inputs.Pic,
		IsR:       0,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	err := conf.Mdb.Create(&messsage).Error

	return &messsage, err
}

func (ms *MessageService) AddRabbit(inputs *message.MessageControllerAdd) (*models.Messages,error) {
	n := nuid.New()
	nuid := n.Next()
	messsage := models.Messages{
		ID:        0,
		MsgID: nuid,
		UserID:    inputs.Userid,
		DstId:     inputs.Dstid,
		Content:   inputs.Content,
		Pic:       inputs.Pic,
		IsR:       0,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	messageJson,_ := json.Marshal(messsage)
	pool,err := rabbitmq.RabbitPoolServe.GetPool()
	pool.CreateExTopic("msg","point")
	pool.CreateQueuen("point")
	if err != nil {
		return nil, err
	}
	err = pool.PublicMSg(string(messageJson), rabbitmq.RabbitPoolServe)
	if err != nil {
		return nil, err
	}
	return &messsage,err
}

func (ms *MessageService) Ack(inputs *message.MessageControllerAck) error {
	messsage := models.Messages{}
	err :=conf.Mdb.Where("id=?",inputs.Id).Take(&messsage).Error
	err = conf.Mdb.Model(&messsage).Where("is_r=?",0).UpdateColumns(map[string]interface{}{"is_r":1, "updated_at": time.Now().Unix()}).Error

	return err
}

func (ms *MessageService) List(where []map[string]interface{}, order string, page int, pageSize int) []models.Messages {
	messagea := []models.Messages{}
	tb := conf.Mdb
	for _,v:= range where {
		for kk, vv := range v {
			tb = tb.Where(kk, vv)
		}
	}
	tb = tb.Order(order)
	tb = tb.Limit(pageSize)
	tb = tb.Offset((page-1)*pageSize)
	tb.Find(&messagea)

	return messagea
}

func (ms *MessageService) AckArr(ids []int) error{
	messsage := []models.Messages{}
	err :=conf.Mdb.Where("id in (?)", ids).Take(&messsage).Error
	err = conf.Mdb.Model(&messsage).Where("is_r=?",0).UpdateColumns(map[string]interface{}{"is_r":1, "updated_at": time.Now().Unix()}).Error

	return err
}
